﻿using UnityEngine;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {
        [CtxMenuItem("SkinnedMeshRenderer/Shapes/Sort",
           "sorts blend-shapes by name", ContextRequirements.HasBlendshapes, 001)]
        public static void SkinnedMeshRendererShapeSorts()
        {
            var contexItem = SkinnContext.GetContextItem();
            if (!contexItem) return;
            var context = contexItem.GetComponent<SkinnedMeshRenderer>();
            if (SkinnEx.IsNullOrNotInAScene(context)) return;
            if (!context.HasSharedMesh()) return;

            var blendshapes = context.GetSharedMesh().GetBlendshapes();
            blendshapes.Sort();

            var mesh = context.GetSharedMesh().Clone() as Mesh;
            mesh.ClearBlendShapes();

            var vertexCount = mesh.vertices.Length;

            for (int i = 0; i < blendshapes.Count; i++)
            {
                var shape = blendshapes[i];
                var frameCount = blendshapes[i].frames.Count;
                for (int ii = 0; ii < frameCount; ii++)
                {
                    var frame = blendshapes[i].frames[ii];
                    mesh.AddBlendShapeFrame(
                        shape.name,
                        frame.frameWeight,
                        !SkinnEx.IsNullOrEmpty(frame.shapeDeltas, vertexCount) ? frame.shapeDeltas : new Vector3[vertexCount],
                        !SkinnEx.IsNullOrEmpty(frame.shapeNormals, vertexCount) ? frame.shapeNormals : null,
                        !SkinnEx.IsNullOrEmpty(frame.shapeTangents, vertexCount) ? frame.shapeTangents : null);
                }
            }

            SkinnContext.UndoRecord(context, "Sort Shapes");
            context.sharedMesh = mesh;

            SkinnContext.Finished();
        }

    }
}